<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="订单号">
              <a-input v-model="queryParam.inOrderCode" placeholder="请输入订单号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="集装箱号">
              <a-input v-model="queryParam.containerNo" placeholder="请输入集装箱号"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="入库库区">
                <j-dict-select-tag
                  v-model="queryParam.area"
                  dictCode="basic_warehouse,warehouse_name,warehouse_code"
                  placeholder="请选择入库库区"
                />
              </a-form-item>
            </a-col>
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="品番类型">
                <a-select v-model="queryParam.goodsType" placeholder="请选择品番类型">
                  <a-select-option value="1">PT品</a-select-option>
                  <a-select-option value="2">市贩品</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <!-- <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <a-form-item label="批次号">
              <a-input v-model="queryParam.batchNumber" placeholder="请输入批次号"></a-input>
            </a-form-item>
          </a-col> -->
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="入库状态">
                <j-dict-select-tag v-model="queryParam.status" dictCode="enter_status" placeholder="请选择入库状态" />
              </a-form-item>
            </a-col>
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="是否挂起">
                <a-select v-model="queryParam.isHangUp" placeholder="请选择挂起状态">
                  <a-select-option value="0">正常</a-select-option>
                  <a-select-option value="1">挂起</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
            <a-col :lg="7" :md="8" :sm="24" :xl="6">
              <a-form-item label="入库时间">
                <j-date
                  v-model="queryParam.inOrderTime_begin"
                  class="query-group-cust"
                  placeholder="请选择开始日期"
                ></j-date>
                <span class="query-group-split-cust"></span>
                <j-date
                  v-model="queryParam.inOrderTime_end"
                  class="query-group-cust"
                  placeholder="请选择结束日期"
                ></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :lg="7" :md="8" :sm="24" :xl="6">
            <span class="table-page-search-submitButtons" style="float: left; overflow: hidden">
              <a-button icon="search" type="primary" @click="searchQuery">查询</a-button>
              <a-button icon="reload" style="margin-left: 8px" type="primary" @click="searchReset">重置</a-button>
              <a style="margin-left: 8px" @click="handleToggleSearch">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button icon="plus" type="primary" @click="handleAdd">新增</a-button>
      <a-upload
        :action="importExcelUrl"
        :headers="tokenHeader"
        :multiple="false"
        :showUploadList="false"
        name="file"
        @change="handleImportExcel"
      >
        <a-button icon="import" type="primary">导入</a-button>
      </a-upload>
      <a-button
        icon="download"
        type="primary"
        @click="
          url.exportXlsUrl = '/inOrder/inOrder/exportXls'
          handleExportXls('入库单')
        "
        >导出
      </a-button>
      <a-button
        icon="download"
        type="primary"
        @click="
          url.exportXlsUrl = '/inOrder/inOrder/importExcel'
          handleExportXls('入库单导入')
        "
        >模版导出
      </a-button>
      <a-button icon="plus" type="primary" @click="showMove(2)">市贩品倒库</a-button>
      <a-button icon="plus" type="primary" @click="showMove(1)">PT品倒库</a-button>
      <a-dropdown v-if="selectedRowKeys.length > 0" v-has="'inOrder:del'">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete" />删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down"/></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择
        <a style="font-weight: 600">{{ selectedRowKeys.length }}</a
        >项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <!-- 选择工作站 -->
      <div style="margin-bottom: 16px">
        <j-dict-select-tag
          v-model="receiveStation"
          dictCode="basic_station_info,station_name,station_code"
          placeholder="请选择工作站"
          style="width: 200px"
        />
      </div>

      <a-table
        ref="table"
        :columns="columns"
        :dataSource="dataSource"
        :loading="loading"
        :pagination="ipagination"
        :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
        :scroll="{ x: true }"
        bordered
        class="j-table-force-nowrap"
        rowKey="id"
        size="middle"
        @change="handleTableChange"
      >
        <template slot="htmlSlot" slot-scope="text">
          <div v-html="text"></div>
        </template>
        <template slot="imgSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无图片</span>
          <img
            v-else
            :src="getImgView(text)"
            alt=""
            height="25px"
            style="max-width: 80px; font-size: 12px; font-style: italic"
          />
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px; font-style: italic">无文件</span>
          <a-button v-else :ghost="true" icon="download" size="small" type="primary" @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.status == '01'" @click="handleEdit(record)" v-has="'inOrder:edit'">编辑</a>
          <a-divider v-if="record.status == '01'" type="vertical" v-has="'inOrder:edit'" />
          <a
            @click="receive(record)"
            v-has="'inOrder:receive'"
            v-if="record.status == '02' || record.taskStatus == '02'"
            >领取任务</a
          >
          <a-divider
            v-has="'inOrder:receive'"
            v-if="record.status == '02' || record.taskStatus == '02'"
            type="vertical"
          />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down"/></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="record.status == '01'" v-has="'inOrder:release'">
                <a @click="release(record)">发布任务</a>
              </a-menu-item>
              <a-menu-item v-if="record.status == '01' || record.status == '02'" v-has="'inOrder:del'">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item>
                <a @click="clickPrintLabel(record)">打印标签</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
    </div>

    <a-modal :title="'打印标签'" :visible="print.show" @ok="confirmPrint()" @cancel="cancelPrint()">
      <a-form>
        <a-form-item label="品番编码">
          <a-select v-model="print.shelfCode" placeholder="请选择品番编码" :showSearch="true">
            <a-select-option v-for="shelfCode in print.shelfCodeOptions" :key="shelfCode" :value="shelfCode">
              {{ shelfCode }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="需要数量">
          <a-input type="number" v-model="print.needQuantity" placeholder="请输入需要数量" />
        </a-form-item>
      </a-form>
    </a-modal>

    <in-order-modal ref="modalForm" @ok="modalFormOk" />
    <a-modal
      title="请输入品番"
      :visible="visible"
      :confirm-loading="confirmLoading"
      @ok="handleOk"
      @cancel="handleCancel"
    >
      <a-input v-model="skuCode" placeholder="请输入品番"></a-input>
    </a-modal>
  </a-card>
</template>

<script>
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import InOrderModal from './modules/InOrderModal'
import '@/assets/less/TableExpand.less'
import JDictSelectTag from '../../../components/dict/JDictSelectTag.vue'
import { downloadFile, postAction } from '../../../api/manage'
import printJS from 'print-js'
import { filterObj } from '@/utils/util'

export default {
  name: 'InOrderList',
  mixins: [JeecgListMixin],
  components: {
    InOrderModal
  },
  JDictSelectTag,
  data() {
    return {
      description: '入库单主表管理页面',
      toggleSearchStatus: true,
      columns: [
        {
          title: '#',
          dataIndex: '',
          key: 'rowIndex',
          width: 60,
          align: 'center',
          customRender: function(t, r, index) {
            return parseInt(index) + 1
          }
        },
        {
          title: '订单号',
          align: 'center',
          dataIndex: 'inOrderCode'
        },
        {
          title: '集装箱号',
          align: 'center',
          dataIndex: 'containerNo'
        },
        {
          title: '入库时间',
          align: 'center',
          dataIndex: 'inOrderTime',
          customRender: function(text) {
            return !text ? '' : text.length > 10 ? text.substr(0, 10) : text
          }
        },
        {
          title: '入库库区',
          align: 'center',
          dataIndex: 'area_dictText'
        },
        // {
        //   title: '批次号',
        //   align: 'center',
        //   dataIndex: 'batchNumber',
        // },
        {
          title: '品番类型',
          align: 'center',
          dataIndex: 'goodsType_dictText'
        },
        {
          title: '入库单状态',
          align: 'center',
          dataIndex: 'status_dictText'
        },
        {
          title: '入库任务状态',
          align: 'center',
          dataIndex: 'taskStatus_dictText'
        },
        {
          title: '备注信息',
          align: 'center',
          dataIndex: 'remarks'
        },
        {
          title: '操作',
          dataIndex: 'action',
          align: 'center',
          fixed: 'right',
          width: 147,
          scopedSlots: { customRender: 'action' }
        }
      ],
      url: {
        list: '/inOrder/inOrder/list',
        delete: '/inOrder/inOrder/delete',
        deleteBatch: '/inOrder/inOrder/deleteBatch',
        exportXlsUrl: '/inOrder/inOrder/exportXls',
        importExcelUrl: 'inOrder/inOrder/importExcel',
        receive: '/inOrder/inOrder/collect',
        isSuspend: '/inOrder/inOrder/isSuspend',
        cancelOrder: '/inOrder/inOrder/cancelOrder',
        release: '/inOrder/inOrder/release',
        getQRCodes: 'inOrder/inOrder/getQRCodes',
        getShelfCodeOptions: '/inOrder/inOrder/getInOrderShelfCodeOptions',
        printLabel: '/inOrder/inOrder/printLabel',
        getIpAddress: '/inOrder/inOrder/getIpAddress'
      },
      dictOptions: {},
      superFieldList: [],
      receiveStation: undefined,
      visible: false,
      confirmLoading: false,
      skuCode: undefined,
      type: undefined,
      print: {
        show: false,
        skuCode: '',
        needQuantity: '',
        shelfCodeOptions: []
      }
    }
  },
  created() {
    this.getSuperFieldList()
    // 获取当前ip默认选择工作站
    this.chooseStation()
  },
  computed: {
    importExcelUrl: function() {
      return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`
    }
  },
  methods: {
    // 获取ip地址
    chooseStation() {
      postAction(this.url.getIpAddress).then(response => {
        if (response.success) {
          const { result } = response

          if ('192.168.10.86' === result) {
            this.receiveStation = 1
          } else if ('192.168.10.222' === result) {
            this.receiveStation = 2
          } else if ('192.168.10.75' === result) {
            this.receiveStation = 3
          }
        }
      })
    },
    // 打印二维码
    printLabel(record) {
      // 发送请求获取Base64图片字符串
      postAction(this.url.printLabel + '?id=' + record.id).then(response => {
        if (response.success) {
          const { result } = response
          const base64List = result.map(base64 => `data:image/png;base64,${base64}`)
          console.log(base64List)

          // 调用api弹出打印预览
          printJS({
            printable: base64List,
            type: 'image',
            base64: true
          })

          this.$message.success('标签打印成功！')
        } else {
          this.$message.warning(response.message)
        }
      })
    },
    //下载二维码
    getQRCodes(record) {
      if (record.area == 'A') {
        return downloadFile(this.url.getQRCodes, 'AGV二维码' + '.zip', { id: record.id })
      } else {
        return downloadFile(this.url.getQRCodes, '高货架二维码' + '.zip', { id: record.id })
      }
    },
    release(record) {
      //发布：创建中→未开始
      if (!record.area || !record.inOrderTime || !record.inOrderCode) {
        this.$message.warning('请补齐当前入库单信息！')
        return
      }
      postAction(this.url.release + '?id=' + record.id).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          this.loadData()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    cancelOrder(id) {
      //取消
      console.log(id)
      postAction(this.url.cancelOrder + '?id=' + id).then(res => {
        if (res.success) {
          this.$message.success(res.message)
          // 新增/修改 成功时，重载列表
          this.loadData()
          //清空列表选中
          this.onClearSelected()
        } else {
          this.$message.warning(res.message)
        }
      })
    },
    receive(record) {
      //领取
      let stationCode = !this.receiveStation ? '' : this.receiveStation
      postAction(this.url.receive + '?id=' + record.id + '&stationCode=' + stationCode).then(res => {
        if (res.success) {
          this.$message.success(res.message)
        } else {
          this.$message.warning(res.message)
        }
        //修改完毕，重新加载数据
        this.loadData()
        console.log(res)
      })
    },
    initDictConfig() {},
    getSuperFieldList() {
      let fieldList = []
      fieldList.push({ type: 'string', value: 'inOrderCode', text: '订单号', dictCode: '' })
      fieldList.push({ type: 'string', value: 'containerNo', text: '集装箱号', dictCode: '' })
      fieldList.push({ type: 'date', value: 'inOrderTime', text: '入库时间' })
      fieldList.push({ type: 'string', value: 'area', text: '入库库区', dictCode: '' })
      fieldList.push({ type: 'int', value: 'goodsType', text: '品番类型', dictCode: '' })
      fieldList.push({ type: 'string', value: 'remarks', text: '备注信息', dictCode: '' })
      this.superFieldList = fieldList
    },

    showMove(type) {
      this.skuCode = undefined
      this.type = type
      this.visible = true
    },
    handleOk(e) {
      this.confirmLoading = true
      let url
      if (this.type == 1) {
        url = '/inOrder/inOrder/addBySkuPt'
      } else if (this.type == 2) {
        url = '/inOrder/inOrder/addBySku'
      } else {
        return
      }
      postAction(url + '?skuCode=' + this.skuCode)
        .then(res => {
          if (res.success) {
            this.loadData()
            this.$message.success(res.message)
            this.visible = false
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.skuCode = undefined
          this.type = undefined
          this.confirmLoading = false
        })
    },
    handleCancel(e) {
      this.visible = false
      this.skuCode = undefined
      this.type = undefined
    },
    getQueryParams() {
      //获取查询条件
      let sqp = {}
      if (this.superQueryParams) {
        sqp['superQueryParams'] = encodeURI(this.superQueryParams)
        sqp['superQueryMatchType'] = this.superQueryMatchType
      }
      var param = Object.assign(sqp, this.queryParam, null, this.filters)
      param.field = this.getQueryField()
      param.pageNo = this.ipagination.current
      param.pageSize = this.ipagination.pageSize
      return filterObj(param)
    },
    clickPrintLabel(record) {
      this.print.show = true

      postAction(this.url.getShelfCodeOptions + '?id=' + record.id).then(response => {
        if (response.success) {
          this.print.shelfCodeOptions = response.result
        }
      })
    },
    confirmPrint() {
      postAction(
        this.url.printLabel + '?skuCode=' + this.print.shelfCode + '&needQuantity=' + this.print.needQuantity
      ).then(response => {
        if (response.success) {
          const { result } = response
          const base64List = result.map(base64 => `data:image/png;base64,${base64}`)
          printJS({
            printable: base64List,
            type: 'image',
            base64: true
          })
          this.$message.success('标签打印成功！')
        } else {
          this.$message.warning(response.message)
        }
        this.cancelPrint()
      })
    },
    cancelPrint() {
      this.print.show = false
      this.print.shelfCode = undefined
      this.print.needQuantity = ''
      this.print.shelfCodeOptions = []
    }
  }
}
</script>
<style scoped>
@import '~@assets/less/common.less';
</style>
